<template>
  <div class="product-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品列表</h2>
      <p>发现优质商品，享受购物乐趣</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称..."
        style="width: 300px; margin-right: 10px"
        @input="handleSearch"
        clearable
      >
        <template #prefix>
          <el-icon><IconSearch /></el-icon>
        </template>
      </el-input>
      
      <el-button type="primary" @click="refreshProducts" :loading="loading">
        <el-icon><IconRefresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 商品网格 -->
    <div v-else-if="products.length > 0" class="product-grid">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id">
          <el-card class="product-card" shadow="hover">
            <div class="product-image">
              <img :src="product.image || '/default-product.jpg'" :alt="product.name" />
            </div>
            <div class="product-info">
              <h3 class="product-title" @click="viewDetail(product.id)">{{ product.name }}</h3>
              <p class="product-price">¥{{ product.price }}</p>
              <p class="product-category">{{ product.category }}</p>
              <div class="product-actions">
                <el-button type="primary" size="small" @click="addToCart(product)" :loading="product.addingToCart">
                  <el-icon><IconShoppingCart /></el-icon>
                  加入购物车
                </el-button>
                <el-button size="small" @click="viewDetail(product.id)">
                  <el-icon><IconView /></el-icon>
                  查看详情
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="暂无商品" :image-size="200">
        <el-button type="primary" @click="refreshProducts">重新加载</el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 24]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

export default {
  name: 'ProductList',
  components: {
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    
    const products = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(8);
    const total = ref(0);
    const searchQuery = ref('');
    const loading = ref(false);
    const searchTimeout = ref(null);

    // 获取商品列表
    const fetchProducts = async () => {
      loading.value = true;
      try {
        let url = `products?page=${currentPage.value}&size=${pageSize.value}`;
        
        if (searchQuery.value) {
          url += `&keyword=${encodeURIComponent(searchQuery.value)}`;
        }
        
        const response = await request.get(url);
        
        if (response.code === 200) {
          const productList = response.data.records || response.data;
          products.value = productList;
          total.value = response.data.total || response.data.length;
        } else {
          ElMessage.error(response.message || '获取商品列表失败');
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        ElMessage.error('获取商品列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 添加到购物车
    const addToCart = async (product) => {
      if (!userStore.isAuthenticated()) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
      }

      product.addingToCart = true;
      try {
        const response = await request.post('/cart/items', null, {
          params: {
            userId: userStore.userId,
            productId: product.id,
            quantity: 1
          }
        });
        
        if (response.code === 200) {
          ElMessage.success('已添加到购物车');
        } else {
          ElMessage.error(response.message || '添加失败');
        }
      } catch (error) {
        ElMessage.error('添加失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        product.addingToCart = false;
      }
    };

    // 查看商品详情
    const viewDetail = (id) => {
      router.push(`/product/${id}`);
    };

    // 防抖搜索
    const handleSearch = () => {
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
      }
      searchTimeout.value = setTimeout(() => {
        currentPage.value = 1;
        fetchProducts();
      }, 500);
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1;
      fetchProducts();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchProducts();
    };

    // 刷新商品列表
    const refreshProducts = () => {
      searchQuery.value = '';
      currentPage.value = 1;
      fetchProducts();
    };

    onMounted(() => {
      fetchProducts();
    });

    return {
      products,
      currentPage,
      pageSize,
      total,
      searchQuery,
      loading,
      userStore,
      fetchProducts,
      addToCart,
      viewDetail,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      refreshProducts
    };
  }
};
</script>

<style scoped>
.product-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.search-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  gap: 10px;
}

.loading-container {
  padding: 40px;
}

.product-grid {
  margin-bottom: 30px;
}

.product-card {
  margin-bottom: 20px;
  transition: transform 0.2s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-2px);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 15px 0;
}

.product-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-title:hover {
  color: #409eff;
}

.product-price {
  font-size: 18px;
  color: #e74c3c;
  font-weight: bold;
  margin: 5px 0;
}

.product-category {
  color: #666;
  font-size: 14px;
  margin: 5px 0 15px 0;
}

.product-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-container {
  text-align: center;
  margin-top: 30px;
}
</style>